﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using SyncList.Business.ValueObject;
using Microsoft.Win32;
using System.Security.Permissions;

namespace SyncList.Business.Services
{
    /// <summary>
    /// Gestion de la base de registres pour l'application
    /// </summary>
    [assembly: RegistryPermissionAttribute(SecurityAction.RequestMinimum, ViewAndModify = "HKEY_CURRENT_USER")]
    class RegistryService : IRegistryService
    {


        /// <summary>
        /// Lire
        /// </summary>
        /// <returns></returns>
        public SyncListSettings Read()
        {
            SyncListSettings result = new SyncListSettings();
            RegistryKey registryKey = GetSyncListKey();

            result.UserName = (string)registryKey.GetValue("UserName");

            return (result);
        }


        /// <summary>
        /// Lire les settings en base de registres en remplissant 
        /// </summary>
        /// <param name="settings">Réglages</param>
        /// <returns></returns>
        public void Read(SyncListSettings settings)
        {
            RegistryKey registryKey = GetSyncListKey();

            settings.UserName = (string)registryKey.GetValue("UserName");            
        }


        /// <summary>
        /// Ecrire 
        /// </summary>
        /// <param name="settings"></param>
        public void Write(SyncListSettings settings)
        {
            RegistryKey registryKey = GetSyncListKey();
            registryKey.SetValue("UserName", settings.UserName);
        }


        /// <summary>
        /// Ouvrir une sous-clé
        /// </summary>
        /// <param name="parent">Clé parente</param>
        /// <param name="path">Chemin</param>
        /// <returns>La sous-sous clé</returns>
        private RegistryKey OpenSubKey(RegistryKey parent, string path)
        {
            RegistryKey currentKey = parent;
            string[] subPaths = path.Split('/');
            foreach (string subPath in subPaths)
            {
                RegistryKey subKey = null;
                subKey = currentKey.OpenSubKey(subPath, true);
                if (subKey == null)
                    subKey = currentKey.CreateSubKey(subPath);
                currentKey = subKey;
            }
            return (currentKey);
        }


        /// <summary>
        /// Renvoie la clé de SyncList
        /// </summary>
        /// <returns></returns>
        private RegistryKey GetSyncListKey()
        {
            RegistryKey registryKey = OpenSubKey(Registry.CurrentUser, "Software/SyncList");
            return (registryKey);
        }

    }
}
